package com.caocaog.market.controller;

import cn.hutool.core.date.DateBetween;
import cn.hutool.core.date.DateUnit;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.dms.dto.BindUserDto;
import com.caocaog.market.dms.dto.QueryOrderDto;
import com.caocaog.market.dms.service.DmsService;
import com.caocaog.market.dms.vo.QueryOrderVo;
import com.caocaog.market.entity.OrderBase;
import com.caocaog.market.entity.OrderPay;
import com.caocaog.market.service.IOrderBaseService;
import com.caocaog.market.service.IOrderPayService;
import com.caocaog.market.service.IShopTakeoutService;
import com.caocaog.market.toccpt.service.ApiForOrderService;
import com.caocaog.market.toccpt.vo.CcptOrderInfo;
import com.caocaog.market.vo.OrderShippedVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.CheckFailedException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品订单信息表
 *
 * @author jeecg-boot
 * @date 2021-11-29
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "orderBase", tags = "商品订单信息表")
@RequestMapping("/order/orderBase")
public class OrderBaseController extends JeecgController<OrderBase, IOrderBaseService> {
    @Autowired
    private IOrderBaseService orderBaseService;
    @Autowired
    private ApiForOrderService apiForOrderService;
    @Autowired
    private IOrderPayService orderPayService;
    @Autowired
    private IShopTakeoutService shopTakeoutService;
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private DmsService dmsService;

    /**
     * 分页列表查询
     *
     * @param orderBase
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商品订单信息表-分页列表查询")
    @ApiOperation(value = "商品订单信息表-分页列表查询", notes = "商品订单信息表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OrderBase orderBase,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OrderBase> queryWrapper = QueryGenerator.initQueryWrapper(orderBase, req.getParameterMap());
        //权限控制 数据筛选
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(orderBase.getShopId())) {
            if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1 != loginUser.getUserType()) {
                if (2 == loginUser.getUserType()) {

                    //分站
                    String siteId = loginUser.getSiteId();
                    queryWrapper.eq("site_id", siteId);

                } else if (3 == loginUser.getUserType()) {
                    //商户
                    String merchantId = loginUser.getMerchantId();
                    //获取门店
                    if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId())) {
                        queryWrapper.eq("shop_id", loginUser.getCurrentSelectedShopId());
                    } else {
                        queryWrapper.eq("merchant_id", merchantId);
                    }

                }
//            queryWrapper.eq("status",1);
            }
        }


        Page<OrderBase> page = new Page<OrderBase>(pageNo, pageSize);
        IPage<OrderBase> pageList = orderBaseService.page(page, queryWrapper);
        for (OrderBase base: pageList.getRecords()){
//            CcptOrderInfo ccptOrderInfo = orderBaseService.getCcptOrderInfo(base);
//            if (oConvertUtils.isNotEmpty(ccptOrderInfo)) {
//                base.setCcptOrderStatus(ccptOrderInfo.getCcptOrderStatus());
//                base.setCcptStaffMobile(oConvertUtils.isEmpty(ccptOrderInfo.getCcptStaffMobile())?"":ccptOrderInfo.getCcptStaffMobile());
//                base.setCcptStaffName(oConvertUtils.isEmpty(ccptOrderInfo.getCcptStaffName())?"":ccptOrderInfo.getCcptStaffName());
//            }
            QueryOrderVo vo = orderBaseService.queryOrderVo(base.getOrderNo(),base.getShopId());
                        if (oConvertUtils.isNotEmpty(vo)) {
                base.setCcptOrderStatus(vo.getStatus());
                base.setCcptStaffMobile(oConvertUtils.isEmpty(vo.getDriverMobile())?"":vo.getDriverMobile());
                base.setCcptStaffName(oConvertUtils.isEmpty(vo.getDriverName())?"":vo.getDriverName());
            }
        }
        return Result.OK(pageList);
    }

    @AutoLog(value = "获取订单其他信息")
    @ApiOperation(value = "获取订单其他信息", notes = "获取订单其他信息")
    @GetMapping(value = "/selectOrderInfo/{id}")
    public Result<?> selectOrderInfo(@PathVariable("id") String id) {

        return Result.OK(orderBaseService.selectOrderInfo(id));
    }

    @AutoLog(value = "获取订单其他信息")
    @ApiOperation(value = "获取订单其他信息", notes = "获取订单其他信息")
    @GetMapping(value = "/selectOrderInfoByOrderNo/{orderNo}")
    public Result<?> selectOrderInfoByOrderNo(@PathVariable("orderNo") String orderNo) {

        return Result.OK(orderBaseService.selectOrderInfoByOrderNo(orderNo));
    }

    /**
     * 添加
     *
     * @param orderBase
     * @return
     */
    @AutoLog(value = "商品订单信息表-添加")
    @ApiOperation(value = "商品订单信息表-添加", notes = "商品订单信息表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody OrderBase orderBase) {
        //订单号生成
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String value = "MO" + format.format(date) + date.getTime();

        orderBase.setOrderNo(value);
        orderBaseService.save(orderBase);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param orderBase
     * @return
     */
    @AutoLog(value = "商品订单信息表-编辑")
    @ApiOperation(value = "商品订单信息表-编辑", notes = "商品订单信息表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody OrderBase orderBase) {
        orderBaseService.updateById(orderBase);
        return Result.OK("编辑成功!");
    }

    /**
     * 订单发货
     * @param orderShippedVO 订单发货VO
     * @return 订单发货结果
     */
    @ApiOperation("订单发货")
    @PostMapping("/shipped")
    public Result<?> shipped(@RequestBody OrderShippedVO orderShippedVO){
        return orderBaseService.orderShipped(orderShippedVO);
    }

    /**
     * 订单后台完成订单
     * @param orderId 订单ID
     * @return 订单发货结果
     */
    @ApiOperation("订单强制完成")
    @PostMapping("/completion/{orderId}")
    public Result<?> completion(@PathVariable String orderId){
        return orderBaseService.orderCompletion(orderId);
    }
    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品订单信息表-通过id删除")
    @ApiOperation(value = "商品订单信息表-通过id删除", notes = "商品订单信息表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        orderBaseService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 通过id删除-商户端
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id删除-商户端")
    @ApiOperation(value = "通过id删除-商户端", notes = "")
    @DeleteMapping(value = "/deleteForMerchant")
    public Result<?> deleteForMerchant(@RequestParam(name = "id", required = true) String id) {

        OrderBase orderBase = orderBaseService.getById(id);
        if (oConvertUtils.isEmpty(orderBase)){
            return Result.error("订单不存在");
        }
        orderBase.setIsShow(1);
        orderBaseService.updateById(orderBase);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品订单信息表-批量删除")
    @ApiOperation(value = "商品订单信息表-批量删除", notes = "商品订单信息表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.orderBaseService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品订单信息表-通过id查询")
    @ApiOperation(value = "商品订单信息表-通过id查询", notes = "商品订单信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        OrderBase orderBase = orderBaseService.getById(id);
        if (orderBase == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(orderBase);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param orderBase
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OrderBase orderBase) {
        return super.exportXls(request, orderBase, OrderBase.class, "商品订单信息表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OrderBase.class);
    }


    @AutoLog(value = "手动发单-商家端")
    @ApiOperation(value = "手动发单-商家端", notes = "param: id:订单ID")
    @GetMapping(value = "/dealMarketManualOrder")
    public Result<?> dealMarketManualOrder(@RequestParam(name = "id", required = true) String id) {

        OrderBase orderBase = orderBaseService.getById(id);
        if (oConvertUtils.isEmpty(orderBase)) {
            return Result.error("参数错误：订单不存在");
        }
        if (!orderBase.getStatus().equals("1")) {
            return Result.error("参数错误：订单并不是待发货状态哦");
        }
       /* ShopTakeout shopTakeout = shopTakeoutService.getOne(new QueryWrapper<ShopTakeout>().eq("shop_id", orderBase.getShopId()));
        if (oConvertUtils.isEmpty(shopTakeout) || !shopTakeout.getOderModel().equals("1")) {
            return Result.error("请勿胡乱操作～非手动发单订单");
        }*/
        //向曹操跑腿手动发单
        OrderPay orderPay = orderPayService.getOne(new QueryWrapper<OrderPay>().eq("order_id", orderBase.getId()));
        if (orderPay.getPayStatus() != 1) {
            return Result.error("请勿胡乱操作～此订单并未支付成功哦");
        }
        if (oConvertUtils.isEmpty(orderPay.getPaySerno())) {
            return Result.error("请稍后操作，此订单异常：" + orderBase.getOrderNo() + " " + orderBase.getStatus());
        }
        Result result = apiForOrderService.dealMarketManualOrder(orderPay.getPaySerno());
        log.info("向曹操跑腿甩单并存甩单记录 isSuccess:" + result.isSuccess() + " " + result.getMessage());
        if (result.isSuccess()) {
            //发单成功 更新用户订单为2待收货
            log.info("发单成功 更新用户订单为2待收货" + orderBase.getOrderNo() + " " + orderBase.getStatus());
            orderBase.setStatus("2");
            orderBaseService.updateById(orderBase);
            orderBaseService.addOrderStatusInfo(orderBase.getId(), orderBase.getOrderNo(), "", "", "商家已接单", new Date());
            return Result.OK("操作成功");
        }else {
            return Result.error(result.getMessage());
        }

    }

    // 核销订单
    @AutoLog(value = "核销订单")
    @ApiOperation(value = "核销订单")
    @GetMapping(value = "/verifyOrder")
    public Result<?> verifyOrder(
            @ApiParam("商家输入的核销码code") @RequestParam("code") String code) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        if (loginUser.getUserType() != 3) {
            return Result.error("暂无权限哦");
        }
        if (oConvertUtils.isEmpty(loginUser.getMerchantId())) {
            return Result.error("操作失败");
        }
        if (code.length()!=6){
            return Result.error("请正确输入核销码");
        }
        String merchantId = loginUser.getMerchantId();
        OrderBase orderBase = orderBaseService.getOne(new QueryWrapper<OrderBase>()
                .eq("merchant_id", merchantId)
                .eq("verify_code", code)
                .last(" limit 1 "));
        if (oConvertUtils.isEmpty(orderBase)) {
            return Result.error("订单不存在,请正确输入核销码~");
        }
        if (!orderBase.getStatus().equals("1")) {
            String dictText =commonAPI.translateDict("order_status", orderBase.getStatus());
            String errorMsg = "订单不是待核销状态:" + orderBase.getOrderNo() + "-" +dictText;
            log.error(errorMsg);
            return Result.error(errorMsg);
        }
        if (!code.equals(orderBase.getVerifyCode())) {
            return Result.error("请正确输入核销码");
        }
        return orderBaseService.verifyOrder(orderBase);
    }

    /**
     * 强制核销-商家端
     *
     * @param orderIds
     * @return
     */
    @AutoLog(value = "强制核销-商家端")
    @ApiOperation(value = "强制核销-商家端订单类型type=2 自提", notes = "params: orderId")
    @GetMapping(value = "/forceVerifyOrder")
    public Result<?> forceVerifyOrder(String[] orderIds) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Date now = new Date();

        for (String orderId : orderIds) {
            OrderBase orderBase = orderBaseService.getById(orderId);
            if (oConvertUtils.isEmpty(orderBase)) {
                return Result.error("参数错误,订单不存在~");
            }
            if (orderBase.getType() != 2) {
                return Result.error("参数错误,订单不是自提单哦~");
            }
            if (!orderBase.getStatus().equals("1")) {
                return Result.error("参数错误,订单不是待核销状态:" + orderBase.getOrderNo() + "-" + orderBase.getStatus());
            }

            if (loginUser.getUserType() != 1) {
                DateBetween dateBetween = DateBetween.create(orderBase.getCreateTime(), now);
                if (dateBetween.between(DateUnit.HOUR) < 24) {
                    int dayMinute = 24 * 60;
                    throw new CheckFailedException(String.format("还未经过24小时，无法进行核销，剩余：%s分钟", dayMinute - dateBetween.between(DateUnit.MINUTE)));
                }
            }

            orderBaseService.verifyOrder(orderBase);
        }
        return Result.OK();
    }



    /**
     * 强制核销，对内使用
     * @param orderNos 订单变化集合
     */
    @GetMapping(value = "/forceVerifyOrderByOrderNo")
    public Result<?> forceVerifyOrderByOrderNo(@RequestParam List<String> orderNos) {
        log.info(String.valueOf(orderNos));
        for (String orderNo : orderNos) {
            OrderBase orderBase = orderBaseService.selectOrderInfoByOrderNo(orderNo);
            if (orderBase.getType() != 2) {
                return Result.error("参数错误,订单不是自提单哦~");
            }
            if (!orderBase.getStatus().equals("1")) {
                String errorMsg = "参数错误,订单不是待核销状态:" + orderBase.getOrderNo() + "-" + orderBase.getStatus();
                log.error(errorMsg);
                return Result.error(errorMsg);
            }
            orderBaseService.verifyOrder(orderBase);
        }
        return Result.OK();
    }



    /**
     * 首页-统计-上
     */
    @ApiOperation(value = "首页-统计-上", notes = "首页-统计-上")
    @GetMapping(value = "/orderCount")
    public Result<?> orderCount(){
        log.info("首页-统计-上");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map map = orderBaseService.orderCount(loginUser.getId(),loginUser);
        return Result.OK(map);
    }

    /**
     * 手动发单到7.0
     * TODO Controller代码直接移植，后续需要重构
     * @param id
     * @return
     */
    @ApiOperation(value = "手动发单-商家端DMS7")
    @GetMapping(value = "/opSendOrderToDMS")
    public Result<?> opSendOrderToDMS(String id) {

        OrderBase orderBase = orderBaseService.getById(id);
        if (oConvertUtils.isEmpty(orderBase)) {
            return Result.error("参数错误：订单不存在");
        }
        if (!orderBase.getStatus().equals("1")) {
            return Result.error("参数错误：订单并不是待发货状态哦");
        }
        //向曹操跑腿手动发单
        OrderPay orderPay = orderPayService.getOne(new QueryWrapper<OrderPay>().eq("order_id", orderBase.getId()));
        if (orderPay.getPayStatus() != 1) {
            return Result.error("请勿胡乱操作～此订单并未支付成功哦");
        }
        if (oConvertUtils.isEmpty(orderPay.getPaySerno())) {
            return Result.error("请稍后操作，此订单异常：" + orderBase.getOrderNo() + " " + orderBase.getStatus());
        }
        Result result = dmsService.opSendOrderToDMS(orderPay.getPaySerno());
        log.info("向曹操跑腿甩单并存甩单记录 isSuccess:" + result.isSuccess() + " " + result.getMessage());
        if (result.isSuccess()) {
            //发单成功 更新用户订单为2待收货
            log.info("发单成功 更新用户订单为2待收货" + orderBase.getOrderNo() + " " + orderBase.getStatus());
            orderBase.setStatus("2");
            orderBaseService.updateById(orderBase);
            orderBaseService.addOrderStatusInfo(orderBase.getId(), orderBase.getOrderNo(), "", "", "商家已接单", new Date());
            return Result.OK("操作成功");
        }else {
            return Result.error(result.getMessage());
        }

    }

    @ApiOperation(value = "查询跑腿账户余额-商家端DMS7")
    @GetMapping(value = "/queryBalanceDMS")
    public Result<BigDecimal> queryBalance( String shopId){
        return dmsService.getBalance(shopId);
    }

    @ApiOperation(value = "绑定跑腿账号-商家端DMS7")
    @PostMapping(value = "/bindDMS")
    public Result<Boolean> bindDMS(@RequestBody BindUserDto bindUserDto){
        if(oConvertUtils.isEmpty(bindUserDto.getUsername()) ||
                oConvertUtils.isEmpty(bindUserDto.getPassword())||
                    oConvertUtils.isEmpty(bindUserDto.getShopId())){
            Result result = new Result();
            return result.error500("参数为空");
        }
        return dmsService.bindUser(bindUserDto);
    }

    @ApiOperation(value = "解绑跑腿账号-商家端DMS7")
    @GetMapping(value = "/unBindDMS")
    public Result<Boolean> unBindDMS(BindUserDto bindUserDto){
        return dmsService.unBindUser(bindUserDto);
    }

    @ApiOperation(value = "查询跑腿订单状态-商家端DMS7")
    @GetMapping(value = "/orderQueryDMS")
    public Result<QueryOrderVo> orderQuery(QueryOrderDto queryOrderDto){
        return dmsService.orderQuery(queryOrderDto);
    }

    @ApiOperation(value = "取消跑腿订单-商家端DMS7")
    @GetMapping(value = "/orderCancelDMS")
    public Result<Boolean> orderCancel(QueryOrderDto queryOrderDto){

        return dmsService.orderCancel(queryOrderDto);
    }

    @ApiOperation(value = "跑腿订单计价-商家端DMS7")
    @GetMapping(value = "/valuationDMS")
    public Result valuationDMS(String id){
        OrderBase orderBase = orderBaseService.getById(id);
        Result result = new Result();
        if (oConvertUtils.isEmpty(orderBase)) {
            return result.error500("参数错误：订单不存在");
        }
        if (!orderBase.getStatus().equals("1")) {
            return result.error500("参数错误：订单并不是待发货状态哦");
        }
        OrderPay orderPay = orderPayService.getOne(new QueryWrapper<OrderPay>().eq("order_id", orderBase.getId()));
        if (orderPay.getPayStatus() != 1) {
            return result.error500("请勿胡乱操作～此订单并未支付成功哦");
        }
        if (oConvertUtils.isEmpty(orderPay.getPaySerno())) {
            return result.error500("请稍后操作，此订单异常：" + orderBase.getOrderNo() + " " + orderBase.getStatus());
        }

        return dmsService.orderValuation(orderPay.getPaySerno());
    }

}
